public class Solution {
    public static String longestPalindrome(String s) {
        String ret = "";
        int len = s.length();
        if (len == 1) {
            return s;
        }
        int left = 0;
        while (left < len) {
            int right = len - 1;
            while (left <= right) {//寻找回文字符串的第一个相同字符
                if (s.charAt(left) != s.charAt(right)) {
                    right--;
                } else {
                    int left1 = left + 1;
                    int right1 = right - 1;
                    while (left1 < right1) {//开始回文判断
                        if (s.charAt(left1) == s.charAt(right1)) {
                            left1++;
                            right1--;
                        } else {
                            break;
                        }
                    }
                    if (left1 >= right1) {
                        ret = (ret.length() > right - left + 1) ? ret : s.substring(left, right + 1);
                        break;
                    }
                }
            }
            left++;
        }
        return ret;
    }

    public String longestPalindrome2(String s) {
        int len = s.length();
        String ret = "";
        for (int i = 0; i < len; i++) {
            //奇数情况
            int left = i, right = i;
            while (left >= 0 && right < len && s.charAt(left) == s.charAt(right)) {
                left--;
                right++;
            }
            ret = ret.length() >= right - left - 1 ? ret : s.substring(left + 1, right);
            //偶数情况
            left = i;
            right = i + 1;
            while (left >= 0 && right < len && s.charAt(left) == s.charAt(right)) {
                left--;
                right++;
            }
            ret = ret.length() >= right - left - 1 ? ret : s.substring(left + 1, right);
        }
        return ret;
    }

    public String longestPalindrome3(String s) {
        int len = s.length();
        char[] ch = s.toCharArray();

        //以i开始、j结尾的子串是否为回文子串
        boolean[][] dp = new boolean[len][len];

        String ret = "";

        for (int i = len - 1; i >= 0; i--) {
            for (int j = len - 1; j >= i; j--) {
                if (ch[i] != ch[j]) {
                    dp[i][j] = false;
                } else {
                    if (i == j || i + 1 == j) {
                        dp[i][j] = true;
                    } else {
                        dp[i][j] = dp[i + 1][j - 1];
                    }
                }
                if (dp[i][j]) {
                    ret = ret.length() > j - i + 1 ? ret : s.substring(i, j + 1);
                }
            }
        }

        return ret;
    }

    public static void main(String[] args) {
        System.out.println(longestPalindrome("ac"));
    }
}
